package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Collect;
import com.dropdb.demo.bean.CollectExample;
import com.dropdb.demo.bean.vo.CollectDataVO;
import com.dropdb.demo.bean.vo.CollectGetListVO;
import com.dropdb.demo.mapper.CollectMapper;
import com.dropdb.demo.service.WxCollectServie;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:cheyanjun
 * @date:2020/06/30 20:08
 */
@Service
public class WxCollectServiceImpl implements WxCollectServie {

    @Autowired
    CollectMapper collectMapper;

    /**
     * 根据用户信息获得收藏列表，并且分页显示
     * @param userId
     * @param type
     * @param page
     * @param size
     * @return 该用户对应的收藏列表
     */
    @Override
    public CollectDataVO getCollectList(int userId, int type, int page, int size) {
        PageHelper.startPage(page, size);
        List<CollectGetListVO> collectGetListVOS = collectMapper.queryList(userId, type);
        PageInfo<CollectGetListVO> pageInfo = new PageInfo<>(collectGetListVOS);
        Long totalPages = pageInfo.getTotal();
        CollectDataVO collectDataVO = new CollectDataVO();
        collectDataVO.setCollectList(collectGetListVOS);
        collectDataVO.setTotalPages(totalPages);
        return collectDataVO;
    }

    /**
     * 增加或删除一个收藏
     * @param userId
     * @param type
     * @param valueId
     * @return 0代表增加，1代表删除
     */
    @Override
    public int queryCollect(int userId, byte type, int valueId) {
        //先查询collect表该用户是否有收藏这个商品，0代表没有，1代表有
        //避免数据重复插入
        int num = collectMapper.queryCollect(userId, type, valueId);
        if (num == 0) {
            //Collect表插入这个商品相关的收藏信息
            Collect collect = new Collect();
            collect.setType(type);
            collect.setUserId(userId);
            collect.setValueId(valueId);
            collect.setDeleted(false);
            collectMapper.insert(collect);
            return 0;
        } else {
            //获取该商品相关的收藏信息，根据deleted判断是否物理删除
            Collect collect = collectMapper.selectCollect(userId, type, valueId);
            //如果物理删除为false，说明此时应该将该条记录的物理删除更新为true
            if (collect.getDeleted() == false) {
                CollectExample collectExample = new CollectExample();
                collectExample.createCriteria().andIdEqualTo(collect.getId());
                collect.setDeleted(true);
                collectMapper.updateByExample(collect, collectExample);
                return 1;
            } else { //如果物理删除为true，说明此时应该将该条记录的物理删除更新为false
                CollectExample collectExample = new CollectExample();
                collectExample.createCriteria().andIdEqualTo(collect.getId());
                collect.setDeleted(false);
                collectMapper.updateByExample(collect, collectExample);
                return 0;
            }
        }

    }
}
